<template>
  <a-card class="user-profile-card">
    <a-row :gutter="32">
      <!-- 左侧：头像 + 昵称 -->
      <a-col :xs="24" :md="8" class="left-section">
        <div class="avatar-wrapper">
          <a-upload :show-upload-list="false" :before-upload="handleAvatarUpload">
            <a-avatar :size="120" :src="avatar" class="avatar-edit" />
          </a-upload>
        </div>
        <div class="nickname">{{ user.username }}</div>
      </a-col>

      <!-- 右侧：用户信息展示或编辑 -->
      <a-col :xs="24" :md="16" class="right-section">
        <a-descriptions title="用户信息" :column="1" v-if="!isEditing">
          <a-descriptions-item label="昵称">{{ user.username }}</a-descriptions-item>
          <a-descriptions-item label="性别">{{
            user.sex === 'male' ? '男' : user.sex === 'female' ? '女' : '保密'
          }}</a-descriptions-item>
          <a-descriptions-item label="出生日期">{{ user.birthdate }}</a-descriptions-item>
          <a-descriptions-item label="个人简介">{{ user.bio }}</a-descriptions-item>
        </a-descriptions>

        <a-form layout="vertical" v-else>
          <a-form-item label="昵称">
            <a-input v-model:value="form.username" />
          </a-form-item>
          <a-form-item label="性别">
            <a-select v-model:value="form.sex" :options="genderOptions" />
          </a-form-item>
          <a-form-item label="出生日期">
            <a-date-picker v-model:value="form.birthdate" />
          </a-form-item>
          <a-form-item label="个人简介">
            <a-textarea v-model:value="form.bio" rows="3" />
          </a-form-item>
        </a-form>

        <!-- 操作按钮 -->
        <div class="actions">
          <a-button type="primary" @click="toggleEdit" v-if="!isEditing">编辑</a-button>
          <a-space v-else>
            <a-button type="primary" @click="submit">提交</a-button>
            <a-button @click="cancelEdit">取消</a-button>
          </a-space>
        </div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs, { type Dayjs } from 'dayjs'
import { getUserInfo, updateUserInfo, uploadAvatar } from '@/http/user'

interface UserInfoType {
  username: string
  birthdate?: string | null | Dayjs
  bio?: string | null
  avatar?: string | null
  sex?: string | null
}
let isEditing = ref(false)

const user = ref<UserInfoType>({
  username: '',
  sex: null,
  birthdate: null,
  bio: null,
})
const avatar = ref('') // 默认头像
const form = ref({ ...user.value })

const genderOptions = [
  { label: '男', value: 'male' },
  { label: '女', value: 'female' },
  { label: '保密', value: null },
]

// 获取用户信息
getUserInfo().then((res) => {
  user.value = res.data
  avatar.value = window.location.origin + '/api/' + res.data.avatar || avatar.value // 如果有头像则使用，否则使用默认
})

const toggleEdit = () => {
  isEditing.value = true
  form.value = { ...user.value }
  if (form.value.birthdate) {
    form.value.birthdate = dayjs(form.value.birthdate) // 确保日期格式正确
  } else {
    form.value.birthdate = null // 如果没有出生日期，设置为 null
  }
}
const cancelEdit = () => {
  isEditing.value = false
}
const submit = () => {
  isEditing.value = false
  if (form.value.birthdate) {
    form.value.birthdate = dayjs(form.value.birthdate).format('YYYY-MM-DD') // 格式化日期
  }
  updateUserInfo({ ...form.value })
    .then((res) => {
      user.value = { ...res.data }
      console.log('更新用户信息成功:', res)
    })
    .catch((error) => {
      console.error('更新用户信息失败:', error)
      message.error('更新失败，请稍后再试')
    })
  message.success('修改成功')
}
const handleAvatarUpload = (file: File) => {
  const reader = new FileReader()
  uploadAvatar(file)
    .then((res) => {
      avatar.value = window.location.origin + '/api/' + res.data.avatar // 更新头像
      message.success('头像上传成功')
    })
    .catch((error) => {
      console.error('头像上传失败:', error)
      message.error('头像上传失败，请稍后再试')
    })
  return false // 阻止默认上传行为
}
</script>

<style scoped lang="scss">
.user-profile-card {
  max-width: 900px;
  margin: 40px auto;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
  .left-section {
    text-align: center;
    .avatar-wrapper {
      position: relative;
      .avatar-edit {
        cursor: pointer;
        border: 2px solid #eee;
        transition: 0.3s;
        &:hover {
          box-shadow: 0 0 0 3px #4096ff40;
        }
      }
    }
    .nickname {
      margin-top: 12px;
      font-size: 18px;
      font-weight: bold;
    }
  }
  .right-section {
    .actions {
      margin-top: 20px;
    }
  }
}
</style>
